package com.white.movies.Adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.white.movies.R;

import java.util.ArrayList;

public class FilmListAdapter<T> extends RecyclerView.Adapter<FilmListAdapter.Viewholder> {
    private ArrayList<T> items;
    private Context context;
    private OnBindDataListener<T> onBindDataListener;

    public FilmListAdapter(ArrayList<T> items, OnBindDataListener<T> onBindDataListener) {
        this.items = items;
        this.onBindDataListener = onBindDataListener;
    }

    @NonNull
    @Override
    public Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.film_viewholder, parent, false);
        return new Viewholder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull Viewholder holder, int position) {
        T item = items.get(position);
        onBindDataListener.onBind(holder, item, position, context);
        holder.itemView.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(position, item);
            }
        });
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }

    // 视图持有者（保持不变，包含item的所有控件）
    public static class Viewholder extends RecyclerView.ViewHolder {
        public TextView titleTxt;
        public ImageView pic;

        public Viewholder(@NonNull View itemView) {
            super(itemView);
            titleTxt = itemView.findViewById(R.id.nameTxt);
            pic = itemView.findViewById(R.id.pic);
        }
    }

    public interface OnBindDataListener<T> {
        void onBind(Viewholder holder, T item, int position, Context context);
    }

    private OnItemClickListener<T> onItemClickListener;

    public interface OnItemClickListener<T> {
        void onItemClick(int position, T item);
    }

    public void setOnItemClickListener(OnItemClickListener<T> listener) {
        this.onItemClickListener = listener;
    }
}